<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        body {
            height: 5000px;
        }
        img {
            position: absolute;
            padding: 10px 0;
            border: 1px solid #ccc;
            cursor: pointer;
            width: 100px;
        }
    </style>
</head>
<body>
<img src="img.jpg" >
<script src="../animate.js"></script>
<script>
    var img = document.getElementsByTagName('img')[0];
    console.log(img);
    var timer = null;
    var targetx = 0,targety=0,leaderx=0,leadery=0;
    document.onclick = function (event) {
        //兼容写法
        event = event || window.event;

        var pageY = event.pageY|| scroll().top+event.clientY,
            pageX = event.pageX || scroll().top + event.clientX;
//        targety = pagey-img.offsetHeight/2;
//            targetx = pagex-img.offsetWidth/2;
        targety = pageY-30;
        targetx = pageX - 50;
        clearInterval(timer);
        timer = setInterval(function () {
            leaderx = img.offsetLeft;
            var stepx = (targetx -leaderx)/10;
            //二次处理步长
            stepx = stepx>0?Math.ceil(stepx):Math.floor(stepx);
            leaderx = leaderx + stepx;
            //赋值
            img.style.left = leaderx + "px";


            //为盒子的位置获取值
            leadery = img.offsetTop;
            //获取步长
            var stepy = (targety-leadery)/10;
            //二次处理步长
            stepy = stepy>0?Math.ceil(stepy):Math.floor(stepy);
            leadery = leadery + stepy;
            //赋值
            img.style.top = leadery + "px";
            //清定时器

                if(Math.abs(targety-img.offsetTop)<=Math.abs(stepy) && Math.abs(targetx-img.offsetLeft)<=Math.abs(stepx)){
                    img.style.top = targety + "px";
                    img.style.left = targetx + "px";

                    clearInterval(timer);
                }

        },25)
    }
</script>
</body>
</html>